from nonebot import on_command
from nonebot.adapters import Bot, Event
from nonebot.typing import T_State
from none_bot_py_plugins.net.socket_main import *
from none_bot_py_plugins.mod.system import system
import time

# 选择角色（选择 uuid）
# 创建角色（创建 角色名）
# 删除角色（删除 uuid）
# 取消（取消）

login = on_command("登陆")
logout = on_command("退出")
select_pl = on_command("选择")
create_pl = on_command("创建")
del_pl = on_command("删除")


class TaskThread(threading.Thread):

    def __init__(self, server_loop):
        super(TaskThread, self).__init__()
        self.__server_loop = server_loop

    def run(self) -> None:
        self.__server_loop.start()


@login.handle()
def login(bot: Bot, event: Event, state: T_State):
    qq_id = event.get_user_id()
    connect_type = "private"
    conn_id = 0
    if getattr(event, "group_id", None):
        conn_id = getattr(event, "group_id")
        connect_type = "group"
    thread_loop = asyncio.new_event_loop()
    task_thread = TaskThread(ServerLoop(qq_id, thread_loop, connect_type, conn_id))
    task_thread.start()
    time.sleep(1)
    socket_main.connect(qq_id)


@logout.handle()
def logout(bot: Bot, event: Event, state: T_State):
    qq_id = event.get_user_id()
    socket_main.disconnect(qq_id)


@select_pl.handle()
def select_player(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    qq_id = event.get_user_id()
    try:
        uuid = int(args)
        system.do_select_player(uuid, qq_id=qq_id)
        await select_pl.finish()
    except Exception:
        await select_pl.finish("输入错误，请重新输入！")


@create_pl.handle()
def create_player(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    qq_id = event.get_user_id()
    system.do_create_player(args, qq_id=qq_id)
    await create_pl.finish()


@del_pl.handle()
def delete_player(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    qq_id = event.get_user_id()
    try:
        uuid = int(args)
        system.do_delete_player(uuid, qq_id=qq_id)
        await select_pl.finish()
    except Exception:
        await select_pl.finish("输入错误，请重新输入！")